package net.zjitc.security.service;

import net.zjitc.entity.Role;
import net.zjitc.entity.User;
import net.zjitc.security.auth.MyGrantedAuthority;
import net.zjitc.security.model.ManageUserDetails;
import net.zjitc.service.IRoleService;
import net.zjitc.service.IUserService;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 认证器，从数据库中取数据进行认证
 */
@Service
@Transactional
public class UserDeatilsServiceImpl implements UserDetailsService {
    @Reference
    private IUserService userService;
    @Reference
    private IRoleService roleService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //从数据库中查询用户
        User user = userService.findByUsername(username);
        if (user == null) {
            //用户名不存在
            return null;
        }
        //查询当前用户角色（）
        //todo
        //角色放在
        List<MyGrantedAuthority> authorityList = new ArrayList<>();
        //一个用户可以有多个角色，本数据库一个用户只有一个角色
        Role role= roleService.selectByid(user.getRoleid());
        //当角色为null或者为0的时候，权限列表为空
        if (role==null){
            authorityList=null;
        }else{
            //从角色列表中拿到角色，并处理角色的权限ids
            String psIds = role.getPsids();
            //如果当前角色的权限ids为空，则不作spilt处理
            if (psIds==null || psIds.length()==0){

            }else {
                String[] split = psIds.split(",");
                //将ids数组转成集合
                List<MyGrantedAuthority> collect = Arrays.asList(split).stream().map(str -> new MyGrantedAuthority(str.toString())).collect(Collectors.toList());
                authorityList.addAll(collect);
            }
        }
        ManageUserDetails userDetails = new ManageUserDetails(user.getUsername(), user.getPassword(), authorityList);
        return userDetails;
    }
}
